<?php

class Materials_Plugin_MaterialVisitors extends Workset_Controller_Plugin_ActionTracer {

    protected $_sessionStorage = null;

    /**
     * Добавляет статистику по просмотру материалов в очередь сообщений
     * 
     * @return void
     */
    function dispatchLoopShutdown() {

        $bootstrap = Zend_Controller_Front::getInstance()->getParam('bootstrap');
        $dbAdapter = $bootstrap->getPluginResource('db')->getDbAdapter();

        if (!$dbAdapter) {
            throw new Zend_Exception('Db adapter is not specified');
        }

        $queueAdapter = new Zend_Queue_Adapter_Db(array(
           'dbAdapter' => $dbAdapter
        ));

        $queue = new Zend_Queue($queueAdapter, array(
           Zend_Queue::NAME => Materials_Model_Material::TYPE,
           Zend_Queue::TIMEOUT => 1,
           Zend_Db_Select::FOR_UPDATE => true
        ));

        $userId = Users_Model_User::getUser()->getId();

        foreach ($this->_requests as $key => $request) {

            $params = $this->_traceParams[$key];

            if (isset($params['identity']) && $params['identity'] > 0) {
                $id =  $params['identity'];

                if (!$this->_isVisited(Materials_Model_Material::TYPE, $id, $userId)) {

                    $material = Materials_Model_Material::getInstance($id);

                    if ($material->getPubDate() > time()) {
                        continue;
                    }
                    
                    $data = array(
                        'identity' => $id,
                        'user_id' => $userId,
                        'owner_id' => $material->getOwnerId(),
                        'pub_date' => $material->getPubDate(),
                        'url' => $request->getRequestUri(),
                    );

                    $queue->send( serialize($data) );
                }
            }
        }
    }

    /**
     * Проверяет добавлен ли просмотр материала
     *
     * @param  string $type - тип события
     * @param  $materialId    - ID просматриваемого материала
     * @param  $userId        - ID текущего пользователя
     * @return bool
     */
    protected function _isVisited($type, $checkSum, $userId) {

        //инициализация сессии
        if (null === $this->_sessionStorage) {
            $this->_sessionStorage = new Zend_Session_Namespace($type);
        }

        //просмотренные материалы
        $data = $this->_sessionStorage->materialVisitor[$userId];

        if (is_array($data) && in_array($checkSum, $data)) {
            return true;
        } else {
            $this->_sessionStorage->materialVisitor[$userId] = array($checkSum);
            return false;
        }
    }

}
